﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using ALiteTeam.PackageTracer.Data;
using ALiteTeam.PackageTracer.Core;
using ALiteTeam.PackageTracer.Core.Impl;
using Microsoft.Expression.Interactivity.Core;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Controls;

namespace ALiteTeam.PackageTracer.ViewModel
{
    public class ComfirmOrderViewModel : ViewModelBase
    {
        public static readonly string INITIALIZE = Guid.NewGuid().ToString();

        public IDeliveryOperate DeliveryOp { get; set; }
        public IOrderOperate OrderOp { get; set; }
        public ILogWrite LogWriter { get; set; }

        public ComfirmOrderViewModel()
        {
            if (base.IsInDesignMode == false)
            {
                this.TextFocusCommand = new RelayCommand(TextBoxFocused, () =>
                {
                    return !string.IsNullOrEmpty(this.Title);
                });

                this.SubmitCommand = new RelayCommand(Submit, () =>
                {
                    return Settings.AppContext.CurrentDeliveryOrder != null;
                });

                this.GoBackCommand = new RelayCommand(GoBack);
                this.SwitchCommand = new RelayCommand(Switch);

                Messenger.Default.Register<NotificationMessage>(this, INITIALIZE, Initialize);
            }
        }

        private void InitializeDependence()
        {
            this.DeliveryOp = DeliveryDataOp.Instance;
            this.OrderOp = new OrderOp();
        }

        public RelayCommand TextFocusCommand { get; private set; }
        private void TextBoxFocused()
        {
            this.Title = string.Empty;
        }

        private void Initialize(NotificationMessage msg)
        {
            this.InitializeDependence();

            var order = Settings.AppContext.CurrentDeliveryOrder;
            var delivery = this.DeliveryOp.DeliveryResource.Deliveries.Where(d => d.ID == order.DeliveryID).FirstOrDefault();

            DeliveryDisplayName = delivery.DisplayName;
            OrderNo = order.OrderNo;            
            IsAutoRefresh = order.IsAutoRefresh;
            RefreshDuration = order.RefreshDuration;

            // 若Title已经输入过值，则保留；否则使用OrderNo代替
            if (string.IsNullOrEmpty(order.Title) == true)
            {
                Title = order.OrderNo;
            }
            else
            {
                Title = order.Title;
            }
        }

        public RelayCommand GoBackCommand { get; private set; }
        public void GoBack()
        {
            // 退回上页之前，保存信息
            var order = Settings.AppContext.CurrentDeliveryOrder;
            order.AddDateTime = DateTime.Now;
            order.OrderNo = this.OrderNo;
            order.Title = this.Title;
            order.IsAutoRefresh = this.IsAutoRefresh;
            order.RefreshDuration = this.RefreshDuration;

            (Application.Current.RootVisual as PhoneApplicationFrame).GoBack();
        }

        public RelayCommand SubmitCommand { get; private set; }
        private void Submit()
        {
            var order = Settings.AppContext.CurrentDeliveryOrder;
            order.AddDateTime = DateTime.Now;
            order.OrderNo = this.OrderNo;
            order.Title = this.Title;
            order.IsAutoRefresh = this.IsAutoRefresh;
            order.RefreshDuration = this.RefreshDuration;

            // 保存到数据库，并清理Setting存储
            OrderOp.AddOrder(order);
            Settings.AppContext.CurrentDeliveryOrder = null;
            Settings.AppContext.SelectedDeliveryID = default(Guid);

            (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri(@"/View/MainPage.xaml?Index=1", UriKind.Relative));
        }

        public RelayCommand SwitchCommand { get; private set; }
        private void Switch()
        {
            if (this.IsAutoRefresh == true && Settings.Configuration.AllowUpdateViaBackground == false)
            {
                if (MessageBox.Show("当前未开启后台更新功能，是否打开？", "提醒", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    ViewModelLocator.SettingsViewModelStatic.AllowUpdateViaBackground = true;
                    ViewModelLocator.SettingsViewModelStatic.AllowToast = true;

                    Messenger.Default.Send<bool>(true, SettingsViewModel.ENALBE_AUTOMATIC_UPDATE);
                }
            }
        }

        private string mDeliveryDisplayName;
        public string DeliveryDisplayName
        {
            get { return mDeliveryDisplayName; }
            set 
            {
                if (mDeliveryDisplayName != value)
                {
                    mDeliveryDisplayName = value;
                    RaisePropertyChanged("DeliveryDisplayName");
                }
            }
        }

        private string mOrderNo;
        public string OrderNo
        {
            get { return mOrderNo; }
            set
            {
                if (mOrderNo != value)
                {
                    mOrderNo = value;
                    RaisePropertyChanged("OrderNo");
                }
            }
        }

        private string mTitle;
        public string Title
        {
            get { return mTitle; }
            set
            {
                if (mTitle != value)
                {
                    mTitle = value;
                    RaisePropertyChanged("Title");
                }
            }
        }

        private bool mIsAutoRefresh;
        public bool IsAutoRefresh
        {
            get { return mIsAutoRefresh; }
            set
            {
                if (mIsAutoRefresh != value)
                {
                    mIsAutoRefresh = value;
                    RaisePropertyChanged("IsAutoRefresh");
                }
            }
        }

        private double mRefreshDuration;
        public double RefreshDuration
        {
            get { return mRefreshDuration; }
            set
            {
                if (mRefreshDuration != value)
                {
                    mRefreshDuration = value;
                    RaisePropertyChanged("RefreshDuration");
                }
            }
        }
    }
}
